<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------

namespace app\user\controller;

use cmf\controller\AdminBaseController;
use think\Db;

/**
 * Class AdminIndexController
 * @package app\user\controller
 *
 * @adminMenuRoot(
 *     'name'   =>'用户管理',
 *     'action' =>'default',
 *     'parent' =>'',
 *     'display'=> true,
 *     'order'  => 10,
 *     'icon'   =>'group',
 *     'remark' =>'用户管理'
 * )
 *
 * @adminMenuRoot(
 *     'name'   =>'用户组',
 *     'action' =>'default1',
 *     'parent' =>'user/AdminIndex/default',
 *     'display'=> true,
 *     'order'  => 10000,
 *     'icon'   =>'',
 *     'remark' =>'用户组'
 * )
 */
class AdminIndexController extends AdminBaseController
{

    /**
     * 后台本站用户列表
     * @adminMenu(
     *     'name'   => '本站用户',
     *     'parent' => 'default1',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '本站用户',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $where   = ['user_type'=>2];
        $param = $this->request->param();

        if (!empty($param['uid'])) {
            $where['id'] = intval($param['uid']);
        }
        $keywordComplex = [];
        if (!empty($param['keyword'])) {
            $keyword = $param['keyword'];

            $keywordComplex['user_nickname|mobile']    = ['like', "%$keyword%"];
        }
        $usersQuery = Db::name('user');

        $list = $usersQuery->alias('a')
            ->join('__DEPARTMENT__ b','a.department_id=b.id','LEFT')
            ->field('a.*,b.name department_name')
            ->whereOr($keywordComplex)->where($where)->order("create_time DESC")->paginate(10);
        $list->appends($param);
        // 获取分页显示
        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);
        // 渲染模板输出
        return $this->fetch();
    }

    /**
     * 添加用户
     * @adminMenu(
     *     'name'   => '添加用户',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加用户',
     *     'param'  => ''
     * )
     */
    public function add(){
        return $this->fetch();
    }

    /**
     * 添加用户提交
     * @adminMenu(
     *     'name'   => '添加用户提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加用户提交',
     *     'param'  => ''
     * )
     */
    public function addPost(){
        $param=$this->request->param();
        $data['user_type']=2;
        $data['mobile']=$param['mobile'];
        $data['user_nickname']=$param['user_nickname'];
        Db::name('user')->insert($data);
        $this->success('添加成功',url('index'));
    }

    /**
     * 删除
     * @adminMenu(
     *     'name'   => '删除',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '删除',
     *     'param'  => ''
     * )
     */
    public function cancelBan()
    {
        $id = input('param.id', 0, 'intval');
        if ($id) {
            Db::name("user")->where(["id" => $id, "user_type" => 2])->delete();
            $this->success("删除成功！", '');
        } else {
            $this->error('数据传入失败！');
        }
    }

    /**
     * 批量导入用户
     * @adminMenu(
     *     'name'   => '批量导入用户',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '批量导入用户',
     *     'param'  => ''
     * )
     */
    public function importUserList(){

        if($this->request->isPost()){
            $file   = $this->request->file('file');
            if(empty($file)){
                echo '请上传文件!';
                return $this->fetch();
            }
            $result = $file->validate([
                'ext'  => 'xlsx',
                'size' => 5*1024 * 1024
            ])->move('.' . DS . 'upload' . DS . 'excel' . DS);


            if ($result) {
                $excelSaveName = str_replace('//', '/', str_replace('\\', '/', $result->getSaveName()));
                $file_path         = './upload/excel/' . $excelSaveName;

                require_once VENDOR_PATH . 'phpoffice/phpexcel/Classes/PHPExcel/IOFactory.php';
                require_once VENDOR_PATH . 'phpoffice/phpexcel/Classes/PHPExcel.php';
                require_once VENDOR_PATH .'phpoffice/phpexcel/Classes/PHPExcel/Shared/Date.php';
                //判断文件版本，选择对应的解析文件
                if ('xlsx' == 'xlsx') {
                    require_once VENDOR_PATH . 'phpoffice/phpexcel/Classes/PHPExcel/Reader/Excel2007.php';
                    $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
                } else {
                    require_once VENDOR_PATH . 'phpoffice/phpexcel/Classes/PHPExcel/Reader/Excel5.php';
                    $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                }
                //解析Excel文件
                $objPHPExcel = $objReader->load($file_path);
                $sheet = $objPHPExcel->getSheet(0);// 读取第一个工作表(编号从 0 开始)
                $highestRow = $sheet->getHighestRow(); // 取得总行数
                //$highestColumn = $sheet->getHighestColumn(); // 取得总列数 列数太多循环失败
                Db::startTrans();
                $num=0;
                $error=0;
                for ($rows = 2; $rows <= $highestRow; $rows++) {
                    $department = trim($objPHPExcel->getActiveSheet()->getCell("A".$rows)->getValue());
                    $data['user_nickname']  = $objPHPExcel->getActiveSheet()->getCell("B".$rows)->getValue();
                    $data['mobile'] = $objPHPExcel->getActiveSheet()->getCell("C".$rows)->getValue();
                    if(!empty($department)){
                        $find1=Db::name('department')->where(['name'=>$department])->value('id');
                        if($find1){
                            $data['department_id']=$find1;
                        }else{
                            $data['department_id']=Db::name('department')->insertGetId(['name'=>$department]);
                        }
                        $find2=Db::name('user')->where(['mobile'=>$data['mobile']])->find();
                        if($find2){
                            $row1=Db::name('user')->where(['id'=>$find2['id']])->update($data);
                        }else{
                            $row1=Db::name('user')->insert($data);
                        }
                        if($row1===false){
                            $error++;
                        }else{
                            $num++;
                        }
                    }
                }

                if ($error===0) {
                    Db::commit();
                    echo "导入成功，共计".$num."条数据";
                } else {
                    Db::rollback();
                    echo "导入失败，共计".$error."条错误，请检查数据";
                }
            } else {
                echo '文件上传失败';
            }
        }
        return $this->fetch();
    }

}
